package com.dzh.spring.tools.excel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.Test;

public class PoiExpExcel {
	@Test
	public  void TestexpExcel() {
		String[] titles = new String[] { "id", "name", "sex" };
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		HSSFRow row = sheet.createRow(0);
		// 设置表头
		for (int i = 0; i < titles.length; i++) {

			HSSFCell cell = row.createCell(i);
			cell.setCellValue(titles[i]);
		}

		for (int i = 1; i <= 10; i++) {
			HSSFRow dataRow = sheet.createRow(i);

			for (int j = 0; j < titles.length; j++) {
				HSSFCell dataCell = dataRow.createCell(j);
				if (titles[j].equals("id")) {
					dataCell.setCellValue("1000" + i);

				} else if (titles[j].equals("name")) {
					dataCell.setCellValue("user" + i);
				} else {
					if (i % 2 == 0)
						dataCell.setCellValue("男");
					else
						dataCell.setCellValue("女");

				}

			}

		}
		File file = new File("d://poi_test.xls");
		try {
			file.createNewFile();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try (FileOutputStream out = new FileOutputStream(file)) {

			workbook.write(out);

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
